import { useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, Row, Col, FormInstance, Button, message } from 'antd'
import { useSelector, useDispatch } from 'react-redux';
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import style from './modifyPasswordModal.module.less'
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons'
import moment from 'moment';
import { Dispatch } from 'redux';
import { sendSMSRequest, modifyPasswordRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool';
import { setSendTime, setToken, setUserInfo } from '@src/redux/actions/basic';
import { clearWindow } from '@src/redux/actions/tab';
import { UserInfo } from '@src/components/schema/basic';
import { setUncompleteMessage, setUncompleteMessageNum } from '@redux/actions/basic';
import { useNavigate, NavigateFunction } from 'react-router-dom';
const { Item } = Form
let timer: NodeJS.Timeout

async function submit (mobile: string, d: { [k: string]: any }, hide: () => void, dispatch: Dispatch, navigate: NavigateFunction) {
  const h = message.loading('修改中', 120)
  const [e] = await awaitWrap(modifyPasswordRequest({
    ...d,
    mobile
  }))
  h()
  if (e === null) {
    message.success('修改成功')
    dispatch(clearWindow())
    dispatch(setToken(''))
    dispatch(setUserInfo({} as UserInfo))
    dispatch(setUncompleteMessage([]))
    dispatch(setUncompleteMessageNum(0))
    hide()
    navigate('/login')
  }
}

async function sendSMS (mobile: string, dispatch: Dispatch) {
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    message.error('手机号格式不正确')
    return undefined
  }
  const hide = message.loading('发送中', 120)
  const [e] = await awaitWrap(sendSMSRequest(mobile))
  if (e === null) {
    message.success('发送成功')
    dispatch(setSendTime(moment().valueOf()))
  }
}

function validator (rule: any, value: string) {
  if (!value) {
    return Promise.resolve()
  }
  if (value.length < 8) {
    return Promise.reject(new Error('最小长度为8位'))
  }
  let count = 0
  if (/[$-]+/.test(value)) {
    return Promise.reject(new Error('新密码不能包含-和$'))
  }
  if (/[a-z]+/.test(value) && /[A-Z]+/.test(value)) {
    count++
  }
  if (/[~!@#%^&*()_+=*/<>?/\\.,;'"]+/.test(value)) {
    count++
  }
  if (/[0-9]+/.test(value)) {
    count++
  }
  if (count < 2) {
    return Promise.reject(new Error('新密码必须包含大小写字母+数字+特殊符号中的两种以上'))
  }
  return Promise.resolve()
}

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props) {
  const [passwordHidable, setPasswordHidable] = useState(false)
  const [loopTime, setLoopTime] = useState(0)
  const formRef = useRef<FormInstance>(null)
  const navigate = useNavigate()
  const { userInfo, sendTime } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      userInfo: state.basic.userInfo,
      sendTime: state.basic.sendTime
    }
  })
  const dispatch = useDispatch()
  useEffect(() => {
    if (sendTime) {
      const time = 60 - Math.ceil((moment().valueOf() - sendTime) / 1000)
      setLoopTime(time > 0 ? time : 0)
    }
  }, [sendTime])
  useEffect(() => {
    if (loopTime > 0 && sendTime) {
      timer && clearTimeout(timer)
      timer = setTimeout(() => {
        const time = 60 - Math.ceil((moment().valueOf() - sendTime) / 1000)
        setLoopTime(time > 0 ? time : 0)
      }, 1000)
    }
  }, [loopTime])
  useEffect(() => {
    const c = formRef.current
    if (visible && c !== null) {
      c.resetFields()
    }
  }, [visible])
  return (
    <Modal
      title='修改密码'
      width={540}
      visible={visible}
      onOk={() => formRef.current?.submit()}
      onCancel={() => hide()}
      maskClosable={false}
      destroyOnClose
    >
      <Form name='new-password' ref={formRef} onFinish={d => submit(userInfo.mobile, d, hide, dispatch, navigate)}>
        <Item label='手机号'>
          <span>{userInfo.mobile || '无'}</span>
        </Item>
        <Item
          name='new_password' label='新密码' rules={[{ required: true, message: '新密码不能为空' }, { validator }]}
        >
          <Input type={passwordHidable ? 'password' : 'text'} placeholder='请输入新密码' suffix={(
            <span className={style['eye-btn']} onClick={() => setPasswordHidable(!passwordHidable)}>
              {passwordHidable ? <EyeInvisibleOutlined /> : <EyeOutlined />}
            </span>
          )} allowClear />
        </Item>
        <Row>
          <Col flex={1}>
            <Item name='verification' label='验证码' rules={[{ required: true, message: '验证码不能为空' }]}>
              <Input maxLength={4} placeholder='请输入验证码' allowClear />
            </Item>
          </Col>
          <Col offset={1}>
            {loopTime ? (
              <Button disabled>{loopTime}秒</Button>
            ) : (
              <Button type='primary' onClick={() => sendSMS(userInfo.mobile, dispatch)} ghost>发送验证码</Button>
            )}
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}

export default Main
